package com.atom.module.mvvm.base.viewmodel

import android.app.Application
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import com.atom.module.mvvm.base.AbstractApplication
import com.atom.module.mvvm.base.ApiModel
import com.atom.module.mvvm.base.ApiViewModel

abstract class AbstractViewModel<M : ApiModel>(val model: M) : ViewModel(), ApiViewModel {

    private var mLifecycleOwner: LifecycleOwner? = null

    override fun onCleared() {
        super.onCleared()
        model.onCleared()
    }

    open fun <T : Application> getApplication(): T {
        return AbstractApplication.getInstance() as T
    }

    override fun setLifecycleOwner(lifecycleOwner: LifecycleOwner) {
        if (lifecycleOwner is Fragment) {
            Log.w(
                "DataBinding", "Setting the fragment as the LifecycleOwner might cause"
                        + " memory leaks because views lives shorter than the Fragment. Consider"
                        + " using Fragment's view lifecycle"
            )
        }
        if (mLifecycleOwner === lifecycleOwner) {
            return
        }
        mLifecycleOwner?.lifecycle?.removeObserver(this)
        mLifecycleOwner = lifecycleOwner
        lifecycleOwner.lifecycle.addObserver(this)
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        if (event >= Lifecycle.Event.ON_DESTROY) {
            onCleared()
        }
    }
}
